package com.xxwy.study.client;

import com.xxwy.study.client.code.OrderFrameDecoder;
import com.xxwy.study.client.code.OrderFrameEncoder;
import com.xxwy.study.client.code.OrderProtocolDecoder;
import com.xxwy.study.client.code.OrderProtocolEncoder;
import com.xxwy.study.client.dispatcher.OperationResultFuture;
import com.xxwy.study.client.dispatcher.RequestPendingCenter;
import com.xxwy.study.client.dispatcher.ResponseDispatcherHandler;
import com.xxwy.study.common.RequestMessage;
import com.xxwy.study.common.order.OrderOperation;
import com.xxwy.study.util.IdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ExecutionException;

/**
 * .
 *
 * @author xxwy
 * @date 2021/11/23 0023
 */
public class Client {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        ResponseDispatcherHandler responseDispatcherHandler = new ResponseDispatcherHandler();

        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new OrderFrameDecoder());
                        pipeline.addLast(new OrderFrameEncoder());
                        pipeline.addLast(new OrderProtocolDecoder());
                        pipeline.addLast(new OrderProtocolEncoder());
                        pipeline.addLast(responseDispatcherHandler);
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666);
        // 等待channel初始化结束
        channelFuture.sync();

        RequestMessage requestMessage = new RequestMessage(IdUtil.nextId(), new OrderOperation(1, "土豆子"));
        RequestPendingCenter pendingCenter = responseDispatcherHandler.getRequestPendingCenter();
        OperationResultFuture operationResultFuture = new OperationResultFuture();
        pendingCenter.add(requestMessage.getMessageHeader().getStreamId(), operationResultFuture);

        channelFuture.channel().writeAndFlush(requestMessage);

        System.out.println("out: " + operationResultFuture.get());
        channelFuture.channel().closeFuture().get();
    }
}
